package com.libui.webview.jsinterface.handlers

import com.libbase.utils.JsonUtils
import com.libbase.utils.ThreadUtils
import com.libui.dialog.DialogEx
import com.libui.dialog.DialogType
import com.libui.webview.WebViewEx
import com.libui.webview.jsinterface.WebViewHandlerInterface
import java.util.*

class AlertHandler : WebViewHandlerInterface {
    companion object {
        const val id: String = "alert"
    }

    override val id: String
        get() {
            return Companion.id
        }

    override fun handle(webView: WebViewEx?, params: Map<String, Any>?) {
        if (webView == null) {
            return
        }

        if (params == null) {
            return
        }

        val uuid: String = params["uuid"] as? String ?: return
        val message: String = params["message"] as? String ?: ""

        ThreadUtils.instance.executeInMainThread {
            webView.context?.let {
                DialogEx
                    .DialogBuilder(
                        DialogType.ALERT,
                        UUID.randomUUID().toString(),
                        message
                    )
                    .setTitle("提示")
                    .setConfirmButtonText("确定")
                    .setInteractiveHide(true)
                    .setCompletion { buttonId ->
                        runSuccessCallback(
                            webView,
                            uuid,
                            0,
                            "alert:ok",
                            JsonUtils.json.toJson(mapOf<String, Any>("action" to (buttonId ?: ""))),
                            params
                        )
                    }
                    .build(it)
                    ?.show()
            }
        }

    }
}